package com.zhou.bjgl.bjgl.Interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zhou.bjgl.bjgl.business_web.service.TokenService;
import com.zhou.bjgl.bjgl.exception.BwException;
import com.zhou.bjgl.bjgl.exception.BwExceptionEnum;
import com.zhou.bjgl.bjgl.myAnnotations.UserLoginToken;
import com.zhou.bjgl.bjgl.req.BaseModel;
import com.zhou.bjgl.bjgl.req.user.UserReq;
import com.zhou.bjgl.bjgl.resp.user.BUserForInfoResp;

import com.zhou.bjgl.bjgl.business_web.service.CommonService;

import com.zhou.bjgl.bjgl.util.RedisUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @ClassName: AuthenticationInterceptor
 * @Description:
 * @Author: zhou
 * @Date: 2022/2/25 14:08
 */
public class AuthenticationInterceptor extends BaseModel implements HandlerInterceptor {


    @Resource
    private CommonService commonService;

    @Resource
    private TokenService tokenService;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object)
            throws Exception {

        String token = request.getHeader("token");

        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method = handlerMethod.getMethod();



        //检查有没有需要用户权限的注解 @UserLoginToken
        if(method.isAnnotationPresent(UserLoginToken.class)){
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if(userLoginToken.required()){
                //开始认证
                if(token==null){
                    throw new BwException(BwExceptionEnum.NO_TOKEN);
                }
                //拿到token中的username
                String username;
                try {
                    username = JWT.decode(token).getAudience().get(0);
                } catch (Exception e) {
                    throw new RuntimeException("401");
                }

                UserReq userReq = new UserReq();
                userReq.setUsername(username);
                BUserForInfoResp user = commonService.getUserInfo(userReq);

                if(user==null){
                    throw new BwException(BwExceptionEnum.USER_NOT_EXIST);
                }

                String tokenInRedis = (String) redisUtil.get(username);

                if (tokenInRedis == null) {
                    throw new BwException(BwExceptionEnum.NO_TOKEN);
                }

                //验证token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                try {
                    BUserForInfoResp bUserForInfoResp = new BUserForInfoResp();
                    DecodedJWT verify = jwtVerifier.verify(token);
                    bUserForInfoResp.setUsername(verify.getClaim("username").asString());
                    bUserForInfoResp.setName(verify.getClaim("name").asString());
                    bUserForInfoResp.setClassName(verify.getClaim("className").asString());
                    bUserForInfoResp.setClassId(verify.getClaim("classId").asLong());
                    bUserForInfoResp.setCollegeId(verify.getClaim("collegeId").asLong());
                    bUserForInfoResp.setPower(verify.getClaim("power").asInt());
                    bUserForInfoResp.setId(verify.getClaim("id").asLong());
                    bUserForInfoResp.setEmail(verify.getClaim("email").asString());
                    bUserForInfoResp.setProfileUrl(verify.getClaim("profile_url").asString());
                    bUserForInfoResp.setPhone(verify.getClaim("phone").asLong());
                    threadLocal.set(bUserForInfoResp);
                } catch (Exception e) {
                    throw new BwException(BwExceptionEnum.NO_TOKEN);
                }

                return true;
            }

        }

        return true;
    }
}
